package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    //@Autowired //是Spring提供的，可以使用Spring的一些特性，例如Spring4 泛型注入
    @Resource //是JDK的注解
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //管理员登录
    public Map login(Map map) {
        //1 获取请求参数
        String uuid = (String) map.get("uuid");
        String verificationCode = (String) map.get("verificationCode");
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        //2 判断账号密码是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new BusinessException("账号和密码不能为空!");
        }

        //3 判断验证码是否为空
        if (StringUtils.isBlank(verificationCode)) {
            throw new BusinessException("验证码不能为空");
        }

        //4 判断验证码是否正确
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (!verificationCode.equals(redisCode)) {
            throw new BusinessException("验证码错误!");
        }

        //5 判断账号密码是否正确
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getUsername, username));
        if (!admin.getPassword().equals(SecureUtil.md5(password))) {
            throw new BusinessException("账号和密码不正确");
        }

        //6 使用工具类创建token
        Map params = new HashMap();
        params.put("id", admin.getId());
        params.put("username", username);

        String token = JwtUtils.getToken(params);

        //7 封装返回的结果数据
        Map retMap = new HashMap();
        retMap.put("token", token);
        return retMap;
    }

    //获取管理员详情
    public AdminVo profile() {
        //1 根据id查询管理员数据
        Admin admin = adminMapper.selectOne(Wrappers.lambdaQuery(Admin.class)
                .eq(Admin::getId, AdminHolder.getUserId()));
        //2 封装vo
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }
}